package vn.com.pavibook.daoImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import vn.com.pavibook.dao.SupportNewsDao;
import vn.com.pavibook.domain.model.SearchResult;
import vn.com.pavibook.domain.model.SupportNews;
import vn.com.pavibook.utils.DaoHelper;

@Repository
public class SupportNewsDaoImpl extends DaoHelper<SupportNews> implements
		SupportNewsDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<SupportNews> getAllSupportNews() {
		String sql = "SELECT * FROM support_news";
		SearchResult<SupportNews> result = query(sql, null,
				new SupportNewsRowMapper());
		if (result == null || result.getSearchResult() == null) {
			return new ArrayList<SupportNews>();
		}
		return result.getSearchResult();
	}

	@SuppressWarnings("rawtypes")
	class SupportNewsRowMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			SupportNews supportNews = new SupportNews();
			supportNews.setId(rs.getInt("id"));
			supportNews.setContent(rs.getString("content"));
			supportNews.setTitle(rs.getString("title"));
			supportNews.setActive(rs.getInt("active"));
			return supportNews;
		}
	}

	@Override
	public void save(SupportNews supportNews) {
		StringBuilder sql = new StringBuilder("");
		Object[] params;
		if (supportNews.getId() != null) {
			sql.append(
					"UPDATE support_news SET title = ?, content = ? , active = ?, url_image = ? ")
					.append(" WHERE id = ?");
			params = new Object[] { supportNews.getTitle(),
					supportNews.getContent(), supportNews.getActive(),
					supportNews.getId() };
		} else {
			sql.append("INSERT INTO support_news (id, title, content, active, url_image) values (?, ?, ?, ?, ?)");
			params = new Object[] { supportNews.getId(),
					supportNews.getTitle(), supportNews.getContent(),
					supportNews.getActive(), supportNews.getUrl_image()};
		}
		
		insert(sql.toString(), params);
	}

	@SuppressWarnings("unchecked")
	@Override
	public SupportNews getSupportNewsById(int id) {
		String sql = "SELECT * FROM support_news WHERE id = ?";
		Object[] params = new Object[] {id};
		SearchResult<SupportNews> result = query(sql.toString(), params, new SupportNewsRowMapper());
		if (result == null || result.getSearchResult() == null) {
			return new SupportNews();
		}
		return result.getSearchResult().get(0);
	}

	@Override
	public void delete(int id) {
		String sql = "DELETE FROM support_news WHERE id = ?";
		Object[] params = new Object[] {id};
		super.delete(sql, params);
	}

}
